#coding=utf-8

from uliweb.orm import *
from uliweb.utils.common import get_var
import datetime
from sqlalchemy.sql import not_

def get_modified_user():
    from uliweb import request
    
    return request.user.id

def get_values(model, ids, condition=None):
    from uliweb.orm import get_model
    model = get_model(model)
    return model.all().filter(condition).values(*ids)

class Requirement(Model):
    __verbose_name__ = u'准开发需求'
    
    req_id = Field(CHAR, verbose_name='编号', max_length=12, required=True, unique=True, index=True)
    tx = Reference('tx', verbose_name='条线', required=True, index=True, collection_name='tx_requirements')
#    year = Field(int, verbose_name='年度', required=True, choices=get_var('PARA/YEAR'), index=True, default=lambda :datetime.date.today().year)
    title = Field(str, verbose_name='标题', max_length=255, required=True)
    description = Field(TEXT, verbose_name='描述')
    mode = Field(CHAR, verbose_name='实施方式', max_length=2, required=True, choices=get_var('PARA/REQ_MODE'))
    stage = Field(CHAR, verbose_name='所处阶段', max_length=20, choices=[], default='00')
    begin_date = Field(datetime.date, verbose_name='阶段开始时间')
    refer_req = Field(CHAR, verbose_name='转入准开发需求', max_length=12)
    memo = Field(TEXT, verbose_name='备注')
    creator = Reference('user', verbose_name='创建者', collection_name='creator_requirements')
    created_date = Field(datetime.date, verbose_name='创建时间', auto_now_add=True)
    modified_date = Field(datetime.datetime, verbose_name='修改时间', auto_now=True, auto_now_add=True)
    modified_user = Reference('user', verbose_name='修改人', collection_name='modifier_requirements', default=get_modified_user, auto=True, auto_add=True)
    main_sys = Reference('system', verbose_name='主系统', required=True, collection_name='main_sys_requirements')
    systems = ManyToMany('system', verbose_name='执行系统', collection_name='sys_requirements')
    care_level = Field(CHAR, verbose_name='关注级别', default='1', choices=get_var('PARA/CARE_LEVEL'))
    kfzxs = ManyToMany('kfzx', verbose_name='开发中心', collection_name='kfzx_requirements')
    attachment = Field(FILE, verbose_name='附件', hint='文件大小不能超过2M，请注意文件大小')
    risk_doc = Field(FILE, verbose_name='风险评估文档', hint='文件大小不能超过2M，请注意文件大小')
    tx_manager = Field(str, max_length=80, verbose_name='条线责任人')
    submitter = Field(str, max_length=80, verbose_name='提出部门')
    contactor = Field(str, max_length=80, verbose_name='业务联系人')
    exe_manager = Field(str, max_length=80, verbose_name='实施负责人')
    selfdev_if = Field(bool, verbose_name='是否参与系统自主率考核',default=True)
    
    def __unicode__(self):
        return u'%s-%s' % (self.req_id, self.title)
    
    def __str__(self):
        return "%s" % self.title
    
    @classmethod
#    def get_user_requirements_choices(cls, user, not_in=('19', '1A', 'FN')):
    def get_user_requirements_choices(cls, user, not_in=()):
        query = cls.get_user_requirements(user, not_in)
        return [(x.id, unicode(x)) for x in query]
        
    @classmethod
#    def get_user_requirements(cls, user, not_in=('19', '1A', 'FN')):
    def get_user_requirements(cls, user, not_in=()):
        #如果是条线，则只能看以条线的准开发需求
        condition = None
        if user.department == '1':
            condition = (cls.c.tx == user._tx_) & condition
        elif user.department == '2':
            if user.is_gm:
                condition = cls.kfzxs.in_(user._kfzx_) & condition
            else:
                ids = user.users_systems.ids()
                condition = cls.systems.in_(*ids) & condition
        if not_in:
            condition = not_(cls.c.stage.in_(not_in)) & condition
        return cls.filter(condition).order_by(cls.c.req_id)
        
    def can_modified(self, user):
        """
        根据用户身份来判断是否可以修改
        """
        if user.is_superuser:
            return True
        
        #条线人员
        if user.department == '1':
            return user._tx_ == self._tx_
        #开发中心人员
        elif user.department == '2':
            return user.users_systems.has(self.main_sys)
        
    def get_url(self):
        return u'<a href="/requirements/%d">%s</a>' % (self.id, unicode(self))
    
#    class Meta:
#        group_field = 'title'
    
    def get_receiver_ids(self, sender_id):
        users = set([self._creator_])
        User = get_model('user')
        test_user = User.filter(User.c.department =='3')
        
        for x in self.systems.all():
            users.update(set(x.users.ids()))
        if sender_id in users:
            users.remove(sender_id)
        for row in test_user:
            if row.id in users:
                users.remove(row.id)
        
        return list(users)
    
    class Meta:
        order_by = 'req_id'
    
    class AddForm:
        fields = ('tx', 'title', 'description', 'attachment', 'mode',  
            'main_sys', 'systems', 'risk_doc','memo', 'tx_manager', 'submitter',
            'contactor', 'exe_manager')
        
    class EditForm:
        fields = ('req_id', 'title', 'description', 'attachment', 'mode', 'stage', 'refer_req', 
            'tx_manager', 'submitter', 'contactor', 'exe_manager',
            'main_sys', 'systems', 'care_level', 'risk_doc', 'memo')
    
    class DetailView:
        fields = ('req_id', 'tx', 'care_level', 'created_date', 'title', 'description', 'attachment', 
            'mode', 'stage', 'refer_req', 'tx_manager', 'submitter', 'contactor', 'exe_manager', 
            'main_sys', 'systems', 'risk_doc', 'memo', 'modified_date', 'modified_user', 'selfdev_if')
    
    class Table:
        fields = [
            {'name':'tx', 'width':60},
            {'name':'req_id'},
            {'name':'care_level', 'width':60},
            {'name':'created_date', 'width':80},
            {'name':'title', 'width':150},
            {'name':'mode'},
            {'name':'stage', 'width':80},
#            {'name':'refer_req', 'width':120},
            'tx_manager', 'submitter', 'contactor', 'exe_manager',
            {'name':'main_sys', 'width':60},
            {'name':'systems', 'width':450},
            {'name':'delay_if','verbose_name':'是否延迟', 'width':70},
            {'name':'plan_stat','verbose_name':'计划进度完成', 'width':80},
            {'name':'inner_resource_num','verbose_name':'中心实际投入资源(人月)', 'width':135},   
            {'name':'inner_input','verbose_name':'中心实际投入资源较计划', 'width':150},
            {'name':'outer_resource_num','verbose_name':'公司实际投入资源(人月)', 'width':135},  
            {'name':'outer_input','verbose_name':'公司实际投入资源较计划', 'width':150}
        ]

class RequirementDetails(Model):
    __verbose_name__ = u'准开发需求明细'
    
    requirement = Reference('requirement', verbose_name="编号", collection_name="details")
    tx = Reference('tx', verbose_name="条线")
    mode = Field(CHAR, verbose_name='实施方式', max_length=2, required=True, choices=get_var('PARA/REQ_MODE'))
    stage = Field(CHAR, verbose_name='所处阶段', max_length=20, choices=[])
    begin_date = Field(datetime.date, verbose_name="开始时间", required=True)
    end_date = Field(datetime.date, verbose_name="结束时间", required=True)
    modified_date = Field(datetime.datetime, verbose_name='修改时间', auto_now=True, auto_now_add=True)
    modified_user = Reference('user', verbose_name='修改人', collection_name='modifier_requirement_details', default=get_modified_user, auto=True, auto_add=True)
    
    @classmethod
    def OnInit(cls):
        Index('requirementdetails_indx', cls.c.requirement, cls.c.stage)
    
class RequirementChange(Model):
    type = Field(CHAR, max_length=1, verbose_name='类型', choices=get_var("PARA/CHANGE_TYPE"), required=True)
    requirement = Reference('requirement', verbose_name="准开发需求")
    change_date = Field(datetime.date, verbose_name='变更时间', required=True)
    content = Field(TEXT, verbose_name="变更内容", required=True)
    according = Field(TEXT, verbose_name="变更依据", required=True, hint="便函，OA，会议纪要等名称或文号")
    modified_date = Field(datetime.datetime, verbose_name='修改时间', auto_now=True, auto_now_add=True)
    modified_user = Reference('user', verbose_name='修改人', default=get_modified_user, auto=True, auto_add=True)

    class AddForm:
        fields = ('type', 'change_date', 'content', 'according')

    class EditForm:
        fields = ('type', 'change_date', 'content', 'according')
    
    class Table:
        fields = [
            'type', 'change_date', 'content', 'according', 'modified_date', 'modified_user',
            {'name':'action', 'verbose_name':'操作'}
            ]